#include "ExpAST.h"
#include "Globe.h"
#include <iostream>
#include "parser.h"
#include "Globe.h"
#pragma warning(disable:4267)
using std::cout;
using std::endl;

unique_ptr<BaseExpAST> parser::parseMulExp()
{
    unique_ptr<BaseExpAST>l = this->parseUnaryExp();
    while (this->lexer->next_token() == TOK::MUL || this->lexer->next_token() == TOK::DIV || this->lexer->next_token() == TOK::MOD)
    {
        unique_ptr<MulAST>t(new MulAST);
        switch (this->lexer->next_token())
        {
        case TOK::MUL:
            t->op = MulAST::MUL;
            break;
        case TOK::MOD:
            t->op = MulAST::MOD;
            break;
        case TOK::DIV:
            t->op = MulAST::DIV;
            break;
        default:
            break;
        }
        this->lexer->match(this->lexer->next_token());
        t->exp1 = std::move(l);
        t->exp2 = this->parseUnaryExp();
        l = std::move(t);
        t = nullptr;
    }
    return l;
}

void MulAST::Dump() const
{
    cout << "{\"type\":\"Mul\",\"op\":\"";
    switch (this->op)
    {
    case MUL:
        cout << "*";
        break;
    case DIV:
        cout << "/";
        break;
    case MOD:
        cout << "%";
        break;
    default:break;
    }
    cout << "\",";
    if (this->op == DEFAULT)
    {
        cout << "\"content\":";
        this->exp1->Dump();
    }
    else
    {
        cout << "\"exp1\":";
        this->exp1->Dump();
        cout << ",\"exp2\":";
        this->exp2->Dump();
    }
    cout << "}";
}


bool MulAST::is_lval() const
{
    if (this->op == DEFAULT)
        return this->exp1->is_lval();
    return false;
}

void MulAST::Analyze() const
{
    if (this->op == MulAST::DEFAULT)
        this->exp1->Analyze();
    else
    {
        this->exp2->Analyze();
        GENASM(cmd_code::PUSH, CVR(EAX), cmd_val());
        this->exp1->Analyze();
        GENASM(cmd_code::POP, CVR(ECX), cmd_val());
        if (this->op == MulAST::MUL) {
            GENASM(cmd_code::IMUL, CVR(EAX), CVR(ECX));
        }
        else {
            GENASM(cmd_code::CLTD, cmd_val(), cmd_val());
            GENASM(cmd_code::IDIV, CVR(ECX), cmd_val());
            if (this->op == MulAST::MOD)
                GENASM(cmd_code::MOV, CVR(EDX), CVR(EAX));
        }
    }
}
